import { reqGetUserDetailById, reqGetUserInfo, reqLogin } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    login(context, data) {
      return new Promise((resolve, reject) => {
        // 发送登录请求
        reqLogin(data).then(res => {
          const newToken = res.data
          context.commit('setToken', newToken)
          // 成功resolve
          resolve(res)
        }).catch(error => {
          // 失败reject
          reject(error)
        })
      })
    },
    async getUserInfo(context, payload) {
      const { data: data1 } = await reqGetUserInfo()
      const { data: data2 } = await reqGetUserDetailById(data1.userId)
      // console.log(res)
      const obj = { ...data1, ...data2 }
      context.commit('setUserInfo', obj)
      return obj
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}
